<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: Participate.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Vote_Form_Photo_Participate extends Vote_Form_Participate {
	public function init() {
		parent::init ();
		
		$this->setTitle ( 'vote_photo_part_CREATE_TITLE' )->setDescription ( 'vote_photo_part_CREATE_DESC' )->setMethod ( 'post' )->setAttrib ( 'class', 'global_form create_voting_form' );
		
		$this->getElement ( 'photo' )->setRequired ( true );
		$this->getElement ( 'photo' )->setAllowEmpty ( false );
		$this->getElement ( 'photo' )->addValidator ( 'NotEmpty', true );
	}
	
	public function participate(Vote_Model_Challenge $voting) {
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$values = $this->getValues ();
		
		if (! $viewer->getIdentity () || empty ( $values ) || ! $voting->getIdentity ()) {
			return false;
		}
		
		if ($voting->isParticipated ( $viewer )) {
			return false;
		}
		
		if ($voting->isFinished ()) {
			return false;
		}
		
		$task = $values ['task'];
		if ($task !== 'participate') {
			return false;
		}
		
		unset ( $values ['task'] );
		$values ['user_id'] = $viewer->getIdentity ();
		$values ['type'] = 'photo';
		$values ['search'] = ( int ) $voting->search;
		$values ['challenge_id'] = ( int ) $voting->getIdentity ();
		$values ['creation_date'] = date ( 'Y-m-d H:i:s' );
		
		$table = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$db = $table->getAdapter ();
		$db->beginTransaction ();
		
		try {
			$row = $table->createRow ();
			$row->setFromArray ( $values );
			$row->save ();
			
			if (! empty ( $values ['photo'] )) {
				$row->setPhoto ( $this->photo );
			}
			
			$voting->participant_count ++;
			$voting->save ();
			
			$activityApi = Engine_Api::_ ()->getDbTable ( 'actions', 'activity' );
			$action = $activityApi->addActivity ( $viewer, $voting, 'vote_participated' );
			
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
		
		return true;
	}
}